'use client'
export const dynamic = 'force-static'
import { useState } from "react";
import PromoProduct from "@/components/PromoProduct";
import { Modal } from "@/components/Modal";
import QRCodeComponent from "@/components/PromoQRCode";
import CircularProgress from "@/components/CircularProgress";
import { getUrlParams } from "@/utils/url";

export default function Home() {
  const [modalOpen, setModalOpen] = useState(false);
  const [qrCodeUrl, setQrCodeUrl] = useState(''); // 新增状态来保存二维码 URL

  const items = [
    { title: "韩束红蛮腰水乳", description: "【520为爱放价】贾乃亮/姜十七抗皱抗糖抗氧补水保湿韩束红蛮腰水乳", image: '/product.png' },
  ];

  const handleButtonClick = async () => {
    const openid = getUrlParams().openid;
    if (!openid) {
      alert('OpenID is missing! Please check and try again.'); // 显示警告提示框
      return; // 终止函数执行，不继续弹出二维码
    }
    try {
      const response = await fetch('/api?openid=' + openid); // 确保 URL 正确拼接
      const data = await response.json(); // 假设服务器返回 JSON 数据包含二维码 URL
      setQrCodeUrl(data.qrcode); // 更新二维码 URL 状态
      setModalOpen(true); // 打开模态框
    } catch (error) {
      console.error('Failed to fetch QR code:', error);
    }
  };

  return (
    <div className="container mx-auto p-4">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {items.map((item, index) => (
          <div key={index} className="flex flex-col items-center bg-white p-4 shadow rounded-lg">
            <PromoProduct
              image={item.image}
              title={item.title}
              description={item.description}
            />
            <CircularProgress className="mt-4 py-2 px-4 text-white font-bold rounded" text="免费领取" onClick={handleButtonClick} color="#ef4444" percentage={0} />
            <Modal isOpen={modalOpen} onClose={() => setModalOpen(false)}>
              <div className="p-8 bg-white rounded-lg shadow-lg max-w-sm text-center">
                <h1 className="text-xl font-semibold mb-4">这是您的专属二维码</h1>
                <p className="text-gray-600 mb-4">邀请好友微信扫码关注，免费领取</p>
                <p>{item.title}</p>
                <QRCodeComponent value={qrCodeUrl} logo={item.image}/> {/* 使用状态值作为属性 */}
                <p className="text-gray-500 text-sm" color="red">绝无套路，绝无套路，绝无套路</p>
              </div>
            </Modal>
          </div>
        ))}
      </div>
    </div>
  );
}
